//
//  MoreViewController.m
//  DaDaBao
//
//  Created by User on 15/8/12.
//  Copyright (c) 2015年 User. All rights reserved.
//
#import "AboutUsViewController.h"
#import "OpinionViewController.h"
#import "MoreViewController.h"
#import "AnnouncementViewController.h"
#import "HelpCenterViewController.h"
#import <ShareSDK/ShareSDK.h>
#import <TencentOpenAPI/QQApi.h>
#import <MessageUI/MFMailComposeViewController.h>

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define iOS8 SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"8.0")
@interface MoreViewController ()<UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate,UIActionSheetDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSArray *dataArray1;
@property(nonatomic,strong)NSArray *dataArray2;
@property (nonatomic, strong) UIButton *loginOutBt;
@property(nonatomic,strong)UIView  *shareView;
@property(nonatomic,strong)UIView  *shareBgView;
@end

@implementation MoreViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [_tableView reloadData];
    [self updateLoginOutBtState];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    [self createSubViews];
    if (!_dataArray1) {
        _dataArray1 = @[@"服务公告",@"帮助中心",@"关于我们",@"客服电话"];
    }
    if (!_dataArray2) {
        _dataArray2 = @[@"应用评分",@"意见反馈",@"转给朋友"];
    }
}

- (void)updateLoginOutBtState //更新按钮的状态
{
    [_loginOutBt setHidden:([[NSUserDefaults standardUserDefaults]objectForKey:@"token"] == nil) ? TRUE : FALSE];
}

#pragma mark-创建视图
-(void)createSubViews
{
//    自定义navgationBar
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [topView setTitile:@"更多"];
    [self.view addSubview:topView];
    
//    建表
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0.0f, topView.frame.origin.y+topView.frame.size.height, SCREEN_WIDTH, SCREEN_HEIGHT - 64.0f - 49.0f) style:UITableViewStyleGrouped];
        _tableView.separatorColor = UITableViewCellSelectionStyleNone;
        _tableView.delegate = self;
        _tableView.dataSource = self;
        [self.view addSubview:_tableView];
        
        UIView *footerView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 100.0f)];
        footerView.backgroundColor = [UIColor clearColor];
        
        _loginOutBt = [[UIButton alloc]initWithFrame:CGRectMake(15.0f, 30.0f, SCREEN_WIDTH-30.0f, 35.0f*HSCALE)];
        _loginOutBt.backgroundColor = [UIColor hexStringToColor:RED_COLOR_VALUE];
        _loginOutBt.titleLabel.font = [UIFont boldSystemFontOfSize:19];
        [_loginOutBt setTitle:@"退出" forState:UIControlStateNormal];
        [_loginOutBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [self updateLoginOutBtState];
        _loginOutBt.layer.cornerRadius = 5.0f;
        _loginOutBt.layer.masksToBounds = TRUE;
        [_loginOutBt addTarget:self action:@selector(buttonLoginOutTapped:) forControlEvents:UIControlEventTouchUpInside];
        [footerView addSubview:_loginOutBt];
        _tableView.tableFooterView = footerView;
    }
    
}

- (void)buttonLoginOutTapped:(id)sender
{
    UIActionSheet *  loginOutAS = [[UIActionSheet alloc]initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"退出" otherButtonTitles:nil];
    [loginOutAS showInView:self.view];
}

#pragma mark -actionDelegate

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if(buttonIndex == 0)
    {
        [AppGlobalClass exitLogin];
        [self updateLoginOutBtState];
    }
}

#pragma mark- tableViewDatasource

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
         
        UILabel *detailLab = [[UILabel alloc] initWithFrame:CGRectMake(SCREEN_WIDTH - 200.0f, 10.0f, 190.0f, 24.0f)];
        detailLab.tag = 1000;
        detailLab.textAlignment = NSTextAlignmentRight;
        [cell addSubview:detailLab];
    }
    
    UILabel *detailLab = (UILabel *)[cell viewWithTag:1000];
    if (indexPath.section==0) {
        cell.textLabel.text = [_dataArray1 objectAtIndex:indexPath.row];
    }
    else{
        cell.textLabel.text = [_dataArray2 objectAtIndex:indexPath.row];

    }
    if (indexPath.row<3) {
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else{
        if (indexPath.section==0) {
            detailLab.text = @"400-8618-778";
        }
    }
    return cell;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section==0) {
        return _dataArray1.count;
        
    }
    else
    {
        return _dataArray2.count;
    }
    
}
#pragma mark- tableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section==0) {
        return 7.5f;
    }
    else{
        return 20.0f;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.01f;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (indexPath.section == 0) {
        switch (indexPath.row) {
            case 0:
            {
                AnnouncementViewController *announcementViewCon = [[AnnouncementViewController alloc]init];
                [self.navigationController pushViewController:announcementViewCon animated:TRUE];
            }
                break;
            case 1:
            {
                HelpCenterViewController *helpCenterVC = [[HelpCenterViewController alloc] init];
                [self.navigationController pushViewController:helpCenterVC animated:TRUE];
            }
                break;
            case 2:
            {
                AboutUsViewController * aboutUsVc = [[AboutUsViewController alloc] init];
                [self.navigationController pushViewController:aboutUsVc animated:TRUE];
            }
                break;
            case 3:
            {
                NSMutableString * str=[[NSMutableString alloc] initWithFormat:@"tel:%@",@"400-8618-778"];
                UIWebView * callWebview = [[UIWebView alloc] init];
                [callWebview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:str]]];
                [self.view addSubview:callWebview];
            }
                break;
                
            default:
                break;
        }
    }else
    {
        switch (indexPath.row) {
            case 0:
            {
                [[UIApplication sharedApplication]openURL:[NSURL URLWithString:@"http://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=1016370002&pageNumber=0&sortOrdering=2&type=Purple+Software&mt=8"]];
            }
                break;
            case 1:
            {
                OpinionViewController * vc = [[OpinionViewController alloc]init];
                [self.navigationController pushViewController:vc animated:TRUE];
            }
                break;
            case 2:
            {
                [self createTheShareView];
            }
                break;
                
            default:
                break;
        }
    }
}
#pragma mark-------share

-(void)createTheShareView
{
    CGFloat btnWidth = (SCREEN_WIDTH-6)/4;
    CGFloat btnHeight = btnWidth;
    if (_shareView==nil) {
       
        _shareView=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _shareView.userInteractionEnabled=TRUE;
        _shareView.backgroundColor=[[UIColor blackColor] colorWithAlphaComponent:0.5];
        
        UIWindow * window = [[UIApplication sharedApplication]keyWindow];
        [window addSubview:_shareView];
        
        UITapGestureRecognizer * gesture=[[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(letTheViewDown:)];
        gesture.numberOfTapsRequired=1;
        gesture.numberOfTouchesRequired=1;
        [_shareView addGestureRecognizer:gesture];
        
        
        _shareBgView=[[UIView alloc]init];
        _shareBgView.frame = CGRectMake(0, SCREEN_HEIGHT , SCREEN_WIDTH, SCREEN_WIDTH/2);
        _shareBgView.backgroundColor=[UIColor whiteColor];
        _shareBgView.userInteractionEnabled=TRUE;
        _shareBgView.backgroundColor = [UIColor hexStringToColor:@"#f8f8f8"];
        _shareBgView.clipsToBounds=TRUE;//为了让子视图也一起随着view做动画
        [_shareView addSubview:_shareBgView];
        
//  创建shareBtn
        
        for (int i=0; i<8; i++) {
            NSArray *nameArr = @[@"微博",@"空间",@"微信",@"朋友圈",@"QQ",@"短信",@"邮件",@""];
            
            ShareButton *btn = [[ShareButton alloc] initWithFrame:CGRectMake(btnWidth*(i%4)+2*(i%4), btnHeight*(i/4)+2*(i/4), btnWidth, btnHeight) image:[UIImage imageNamed:[NSString stringWithFormat:@"sharing%d",i+1]] title:[nameArr objectAtIndex:i]];
                       [btn setTitleLabelFont:[UIFont systemFontOfSize:12.0f]];
            btn.backgroundColor = [UIColor whiteColor];
            [btn addTarget:self action:@selector(buttonShareTheContentTapped:) forControlEvents:UIControlEventTouchUpInside];
            btn.tag = 1000+i;
            [_shareBgView addSubview:btn];
            
        }
   }
    
    [UIView animateWithDuration:0.4 animations:^{
       
        _shareBgView.hidden = FALSE;
        _shareView.hidden = FALSE;
        _shareBgView.frame = CGRectMake(0, SCREEN_HEIGHT - SCREEN_WIDTH/2, SCREEN_WIDTH, SCREEN_WIDTH/2);
        
    }];
    
}
#pragma mark-shareBtn方法
-(void)buttonShareTheContentTapped:(id)sender
{
    _shareBgView.userInteractionEnabled = FALSE;
    ShareButton *btn = (ShareButton *)sender;
    
    NSString *content = @"我正在使用大大宝手机客户端，你也快来下载吧！@value(url)";

    switch (btn.tag) {
        case 1000:
        {
            [self createShareString:content withType:SSDKPlatformTypeSinaWeibo];

        }
            break;
        case 1001:
        {

            [self createShareString:content withType:SSDKPlatformSubTypeQZone];

        }
            break;
        case 1002:
        {
            [self createShareString:content withType:SSDKPlatformSubTypeWechatSession];

        }
            break;
        case 1003:
        {
            [self createShareString:content withType:SSDKPlatformSubTypeWechatTimeline];

        }
            break;
        case 1004:
        {
            [self createShareString:content withType:SSDKPlatformSubTypeQQFriend];

        }
            break;
        case 1005:
        {
            [self createShareString:content withType:SSDKPlatformTypeSMS];
            

        }
            break;
        case 1006:
        {
            [self sendMailInApp:content];

        }
            break;
        case 1007:
        {
            btn.enabled = FALSE;
        }
            break;

        default:
            break;
    }
}
-(void)createShareString:(NSString *)content withType:(SSDKPlatformType)type
{
    //创建分享参数
    NSMutableDictionary *shareParams = [NSMutableDictionary dictionary];
    
    [shareParams SSDKSetupShareParamsByText:content
                                     images:@[[UIImage imageNamed:@"Icon"]]
                                        url:[NSURL URLWithString:@"https://www.dadabao.net:8280/dadabaoApp/apptool/app/appdownview/down/appDown?businessAppType=6"]
                                      title:@"大大宝"
                                       type:SSDKContentTypeAuto];
    
    //进行分享
    [ShareSDK share:type
         parameters:shareParams
     onStateChanged:^(SSDKResponseState state, NSDictionary *userData, SSDKContentEntity *contentEntity, NSError *error) {
         
         switch (state) {
             case SSDKResponseStateSuccess:
             {
                 [self showAlert];
                 
                 break;
             }
             case SSDKResponseStateFail:
             {
                 UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享失败"
                                                                     message:[NSString stringWithFormat:@"%@", [[error userInfo] objectForKey:@"error_message"]]
                                                                    delegate:self
                                                           cancelButtonTitle:@"确定"
                                                           otherButtonTitles:nil];
                 [alertView show];
                 break;
             }
             case SSDKResponseStateCancel:
             {
                 [self snapViewBack];

                 break;
             }
             default:
                 break;
         }
         
     }];

}
-(void)showAlert
{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"分享成功"
                                                            message:nil
                                                           delegate:self
                                                  cancelButtonTitle:@"确定"
                                                  otherButtonTitles:nil];
        [alertView show];
    
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [self snapViewBack];
}
-(void)buttonCancelTheViewTapped:(id)sender
{
    [self snapViewBack];//将view滑下去
}
//view滑下去的方法
-(void)snapViewBack
{
    [UIView animateWithDuration:0.4 animations:^{
        
        _shareBgView.frame = CGRectMake(0, SCREEN_HEIGHT, SCREEN_WIDTH, SCREEN_WIDTH/2);
        
    } completion:^(BOOL finished) {
        _shareBgView.userInteractionEnabled = TRUE;

        _shareBgView.hidden = TRUE;
        _shareView.hidden = TRUE;

    }];
    
}

-(void)letTheViewDown:(UITapGestureRecognizer *)geture
{
    [self snapViewBack];
}

#pragma mark------------buttonTapped-------------

-(void)attitudeSnapShare:(UIButton *)btn
{
    [self snapViewBack];
}

- (void)sendMailInApp:(NSString *)content
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (!mailClass) {
        ALERT_VIEW(@"当前系统版本不支持应用内发送邮件功能，您可以使用mailto方法代替");
        [self snapViewBack];

        return;
    }
    if (![mailClass canSendMail]) {
        ALERT_VIEW(@"用户没有设置邮件账户");
        [self snapViewBack];

        return;
    }
    [self createShareString:content withType:SSDKPlatformTypeMail];

}



-(void)dealloc
{
    [_shareView removeFromSuperview];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
